package com.ruoyi.task;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.controller.UserDeviceDataController;
import com.ruoyi.domain.UserDeviceData;
import com.ruoyi.service.UserDeviceDataService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: UserDeviceDataSseTask
 * @Description:
 * @author: lifei
 * @date: 2025年02月24日 15:00
 */
@Component
public class UserDeviceDataSseTask {

    private final UserDeviceDataService dataService = SpringUtils.getBean(UserDeviceDataService.class);

    // 定时任务，每秒执行一次
    @Scheduled(fixedRate = 1000)
    public void pushLatestData() {
        // 遍历所有连接的客户端
        for (Map.Entry<Long, SseEmitter> entry : UserDeviceDataController.getSseEmitters().entrySet()) {
            Long userId = entry.getKey();
            SseEmitter emitter = entry.getValue();

            try {
                // 查询最新数据
                List<UserDeviceData> latestData = dataService.getUserLatestData(userId);
                System.out.println("推送给用户 " + userId + " 的数据: " + latestData); // 添加日志

                // 发送数据到前端
                emitter.send(latestData);
            } catch (Exception e) {
                System.err.println("推送失败，用户ID：" + userId + "，错误：" + e.getMessage());
                // 发送失败则移除连接
                emitter.completeWithError(e);
            }
        }
    }

    // 辅助方法获取 Map
    public static Map<Long, SseEmitter> getSseEmitters() {
        return UserDeviceDataController.getSseEmitters();
    }
}
